import api from './api.js';
import { showMessage } from './common.js';

// 初始化注册表单
function initRegisterForm() {
    const registerForm = document.getElementById('register-form');
    if (!registerForm) return;

    registerForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        const username = document.getElementById('username').value.trim();
        const password = document.getElementById('password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        const email = document.getElementById('email').value.trim();

        // 表单验证
        if (!username || !password || !confirmPassword || !email) {
            showMessage('warning', '请填写所有必填项');
            return;
        }

        if (password !== confirmPassword) {
            showMessage('warning', '两次输入的密码不一致');
            return;
        }

        if (password.length < 6) {
            showMessage('warning', '密码长度不能少于6位');
            return;
        }

        try {
            const response = await api.auth.register({
                username,
                password,
                email
            });

            if (response && response.success) {
                showMessage('success', '注册成功，请登录');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1500);
            } else {
                showMessage('error', response?.message || '注册失败');
            }
        } catch (error) {
            console.error('注册错误:', error);
            showMessage('error', '注册失败，请重试');
        }
    });
}

// 初始化登录链接
function initLoginLink() {
    const loginLink = document.getElementById('login-link');
    if (loginLink) {
        loginLink.addEventListener('click', (e) => {
            e.preventDefault();
            window.location.href = 'login.html';
        });
    }
}

// 页面加载时执行
document.addEventListener('DOMContentLoaded', () => {
    initRegisterForm();
    initLoginLink();
});